<template>
  <div>
    <div>
      <q-btn label="设置种子" @click="showSeedPromt" />
    </div>
    <div>
      <input multipleDisable ref="xlsInput" type="file" @change="addFile" />
      <q-btn
        :disable="btnTransferDisabled"
        color="primary"
        label="开始转账"
        @click="confirmTransfer"
      />
    </div>
    <div>
      <table>
        <tr>
          <th></th>
          <th>金额</th>
          <th>付款地址</th>
          <th>收款地址</th>
          <th>状态</th>
        </tr>
        <tr v-for="(item, index) in list" :key="index">
          <td><q-checkbox v-model="item.selected" /></td>
          <td>{{ item.amount }}</td>
          <td>{{ item.from_addr }}</td>
          <td>{{ item.to_addr }}</td>
          <td>{{ item.state | stateText }}</td>
        </tr>
      </table>
    </div>
    <q-dialog v-model="prompt" persistent>
      <q-card style="min-width: 350px">
        <q-card-section>
          <div class="text-h6">你的种子(字符串):</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          <q-input
            dense
            v-model="text"
            autofocus
            @keyup.enter="prompt = false"
          />
        </q-card-section>

        <q-card-actions align="right" class="text-primary">
          <q-btn flat label="取消" v-close-popup />
          <q-btn flat label="确认" v-close-popup @click="setSeed" />
        </q-card-actions>
      </q-card>
    </q-dialog>
    <q-dialog v-model="doTransferFlag" persistent>
      <q-card>
        <q-card-section class="row items-center">
          <!-- <q-avatar icon="signal_wifi_off" color="primary" text-color="white" /> -->
          <span class="q-ml-sm">确认开始转账吗?</span>
        </q-card-section>

        <q-card-actions align="right">
          <q-btn flat label="取消" color="primary" v-close-popup />
          <q-btn
            flat
            label="开始"
            color="primary"
            v-close-popup
            @click="doTransfer"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script>
import XLSX from "xlsx";
import TransferService from "@/js/transfer/transfer.js";
// https://www.npmjs.com/package/xlsx
// http://demo.haoji.me/2017/02/08-js-xlsx/
export default {
  data() {
    return {
      doTransferFlag: false,
      btnTransferDisabled: false,
      prompt: false,
      text: "",
      seed: "",
      list: [],
      service: new TransferService(),
      tradeId: "",
      intervalId: -1,
    };
  },
  methods: {
    addFile(e) {
      let file = e.target.files[0];
      var that = this;
      var fileReader = new FileReader();
      fileReader.onload = function (ev) {
        console.log(ev, "ev");
        try {
          var data = ev.target.result,
            workbook = XLSX.read(data, {
              type: "binary",
            }), // 以二进制流方式读取得到整份excel表格对象
            list = []; // 存储获取到的数据
        } catch (e) {
          console.log("文件类型不正确");
          return;
        }
        // 表格的表格范围，可用于判断表头是否数量是否正确
        var fromTo = "";
        // 遍历每张表读取
        for (var sheet in workbook.Sheets) {
          //   if (workbook.Sheets.hasOwnProperty(sheet)) {
          fromTo = workbook.Sheets[sheet]["!ref"];
          console.log(fromTo);
          list = list.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
          break; // 如果只取第一张表，就取消注释这行
          //   }
        }

        if (that.intervalId !== -1) {
          clearInterval(that.intervalId);
        }

        that.list = [];
        for (var i in list) {
          let txid = that.$utils.randomString(32);
          that.list.push({
            selected: true,
            amount: list[i].金额,
            from_addr: list[i].转出钱包地址,
            to_addr: list[i].转入钱包地址,
            state: 0,
            txid: txid,
          });
        }
        that.$refs.xlsInput.value = "";
      };
      // 以二进制方式打开文件
      fileReader.readAsBinaryString(file);
    },
    async doTransfer() {
      this.btnTransferDisabled = true;
      if (this.seed === "") {
        alert("请设置种子");
      }
      if (this.list.length <= 0) {
        alert("请设置转账信息");
      }
      this.tradeId = this.$utils.randomString(32);
      this.$utils.setValue("trade_id", this.tradeId);
      const lst = this.list.filter((item) => item.selected);
      let res = await this.service.doTransfer1(this.seed, this.tradeId, lst);
      console.log(res);
      if (res.data.state === 1) {
        this.$toast("已经加入请求队列");
        for(var index in lst) {
          this.$set(lst[index], 'state', 2);
        }
        this.intervalId = setInterval(this.queryTransfer, 5000);
      } else {
        this.$toast(res.data.message);
      }
      this.btnTransferDisabled = false;
    },
    confirmTransfer() {
      this.doTransferFlag = true;
    },
    showSeedPromt() {
      this.text = this.seed;
      this.prompt = true;
    },
    setSeed() {
      this.seed = this.text;
      this.$utils.setValue("seed", this.seed);
    },
    async queryTransfer() {
      try {
        var count = 0;
        let res = await this.service.queryTransfer(this.tradeId);
        console.log(res);
        if (res.data.state === 1) {
          let lst = res.data.list;
          if (this.list.length === 0) {
            this.list = lst;
            return;
          }
          for (var index in lst) {
            let item = this.list.find((val) => val.txid == lst[index].txid);
            console.log(lst[index].state);
            if (item && lst[index].state != 0) {
              this.$set(item, "state", lst[index].state);
              count++;
            }
          }
        }
        // 查询到全部状态后,清楚查询
        if (count == this.list.length) {
          clearInterval(this.intervalId);
        }
      } catch (err) {
        console.log(err.message);
      }
    },
  },
  mounted: function () {
    // this.$utils.setValue("trade_id", "Etf6xwzhmeSkMFbNmE4wJFbNsp2xPQQZ");
    this.tradeId = this.$utils.getValue("trade_id");
    this.intervalId = setInterval(this.queryTransfer, 5000);
    this.seed = this.$utils.getValue("seed");
  },
  filters: {
    stateText(val) {
      if (!val) {
        return "";
      }
      if (val === 2) {
        return "转账中";
      }
      if (val === 4) {
        return "转账成功";
      }
      if (val === 8) {
        return "转账失败";
      }
      if (val === 0) {
        return "队列中";
      }
      return "";
    },
  },
};
</script>

<style scoped>
div {
  margin: 10px;
}
table {
  width: 100%;
  padding: 0;
  margin: 0;
}

caption {
  padding: 0 0 5px 0;
  width: 700px;
  font: italic 11px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
  text-align: right;
}

th {
  font: bold 11px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
  color: #4f6b72;
  border-right: 1px solid #c1dad7;
  border-bottom: 1px solid #c1dad7;
  border-top: 1px solid #c1dad7;
  letter-spacing: 2px;
  text-transform: uppercase;
  text-align: left;
  padding: 6px 6px 6px 12px;
  background: #cae8ea no-repeat;
}

th.nobg {
  border-top: 0;
  border-left: 0;
  border-right: 1px solid #c1dad7;
  background: none;
}

td {
  border-right: 1px solid #c1dad7;
  border-bottom: 1px solid #c1dad7;
  background: #fff;
  font-size: 11px;
  padding: 6px 6px 6px 12px;
  color: #4f6b72;
}

td.alt {
  background: #f5fafa;
  color: #797268;
}

th.spec {
  border-left: 1px solid #c1dad7;
  border-top: 0;
  background: #fff no-repeat;
  font: bold 10px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
}

th.specalt {
  border-left: 1px solid #c1dad7;
  border-top: 0;
  background: #f5fafa no-repeat;
  font: bold 10px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
  color: #797268;
}
</style>
